package com.wryyyyy.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.wryyyyy.dto.PageBean;
import com.wryyyyy.dto.Result;
import com.wryyyyy.dto.UserDTO;
import com.wryyyyy.entity.*;
import com.wryyyyy.mapper.DishMapper;
import com.wryyyyy.mapper.HistMapper;
import com.wryyyyy.mapper.LabelMapper;
import com.wryyyyy.service.IDishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wryyyyy.utils.ImageUtil;
import com.wryyyyy.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.wryyyyy.utils.RedisConstants.*;
import static com.wryyyyy.utils.SystemConstants.DISH_IMAGE_PATH;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wryyyyy
 * @since 2023-11-12
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private DishMapper dishMapper;
    @Resource
    private HistMapper histMapper;
    @Resource
    private LabelMapper labelMapper;

    @Override
    public Result queryById(String id) {
        String key = CACHE_DISH_KEY + id;

        // 1.从Redis查询商户缓存
        String dishJson = stringRedisTemplate.opsForValue().get(key);
        // 2.判断是否存在
        Dish dish = null;
        if (StrUtil.isNotBlank(dishJson)) {
            // 3.存在，转成Java对象返回
            dish = JSONUtil.toBean(dishJson, Dish.class);
            return Result.ok(dish);
        }
        // 4.不存在，根据id查询数据库
        dish = dishMapper.selectDishById(id);

        // 5.不存在，返回错误
        if (dish == null) {
            //将空值写入Redis
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            //返回错误信息
            return Result.fail("菜品信息不存在！");
        }
        // 6.存在
        // 6.1 处理图片
        dish.setUrls(ImageUtil.getUrls(dish.getImages(), DISH_IMAGE_PATH));
        // 6.2 添加标签
        List<Label> labels = labelMapper.selectLabel(dish.getId(), null);
        dish.setLabels(labels);
        // 6.3 写入Redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(dish), CACHE_DISH_TTL, TimeUnit.MINUTES);
        // 6.3 记录hist
        UserDTO user = UserHolder.getUser();
        if (user != null) {
            Hist hist = new Hist();
            hist.setDishId(dish.getId());
            hist.setUserId(user.getId());
            histMapper.insert(hist);
        }
        // 7.返回
        return Result.ok(dish);
    }

    @Override
    @Transactional//添加事务
    public Result update(Dish dish) {
        String id = dish.getId();
        if (id == null) {
            return Result.fail("菜品id不能为空");
        }
        // 1.更新数据库
        updateById(dish);
        // 2.删除缓存
        stringRedisTemplate.delete(CACHE_DISH_KEY + id);
        // 3.返回结果
        return Result.ok();
    }

    @Override
    public Result deleteById(String id) {
//        if (dishMapper.deleteById(id) > 0) {
//            return Result.ok();
//        }
//        return Result.fail("操作失败");
        // 1.更新数据库
        removeById(id);
        // 2.删除缓存
        stringRedisTemplate.delete(CACHE_DISH_KEY + id);
        // 3.返回结果
        return Result.ok();
    }

    @Override
    public Result queryByCondition(String name, Integer current, Integer size, Integer number) {
        Integer start = (current - 1) * size;
        List<Dish> dishes = dishMapper.selectByCondition(name, start, size);
        for (Dish dish : dishes) {
            dish.setUrls(ImageUtil.getOneUrl(dish.getImages(), DISH_IMAGE_PATH));
            List<Label> labels = labelMapper.selectLabel(dish.getId(), number);
            dish.setLabels(labels);
        }

        Integer count = dishMapper.countByCondition(name);

        return Result.ok(new PageBean<>(dishes, count));
    }
}
